package com.health.system.service.system.impl;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.page.PageRequest;

import com.health.system.dao.system.RoleDao;
import com.health.system.dao.system.UserDao;
import com.health.system.dao.system.UserRoleDao;
import com.health.system.javacommon.base.BaseManager;
import com.health.system.javacommon.base.EntityDao;
import com.health.system.javacommon.util.DateUtil;
import com.health.system.javacommon.util.EncodeDecodeUtil;
import com.health.system.springSecurity.LogonUser;
import com.health.system.javacommon.util.StringTool;
import com.health.system.model.system.Role;
import com.health.system.model.system.User;
import com.health.system.model.system.UserRole;
import com.health.system.service.system.UserManager;
import com.health.system.springSecurity.UserInfo;

/**
 * <p>Title: 系统 操作员  业务处理层 </p>
* Description: spring事务实现层,调用Dao层取数据.健康通 
 * Copyright: Copyright (c) 2011-03 
 * Company: 
 * 
 * @author 鲍忠启
 * @version 1.0
 */

@Component("userManager")
@Transactional
public class UserManagerImpl extends BaseManager<User, java.lang.String>
		implements UserManager {

	private UserDao userDao;
	private UserRoleDao userRoleDao;
	private RoleDao roleDao;
	
	
	/** 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性 */
	public void setUserDao(UserDao dao) {
		this.userDao = dao;
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public RoleDao getRoleDao() {
		return roleDao;
	}
	
	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}
	
	public UserRoleDao getUserRoleDao() {
		return userRoleDao;
	}

	public void setUserRoleDao(UserRoleDao userRoleDao) {
		this.userRoleDao = userRoleDao;
	}

	public EntityDao getEntityDao() {
		return this.userDao;
	}
	/**
	 * <p>title:查询登录用户信息</p>
	 * @param name String login.jsp的登录名+,+机构代码 组成
	 */
	public User getUserByName(String name) {
		String[] temp = StringTool.SplitString(name, ",");
		System.out.println("user is : "+name + ",temp.length="+temp.length);
		String j_username ="";
		String j_organCode = "";
		if(null!=temp&&temp.length>=2){
			 j_username = temp[0];
			 j_organCode = temp[1];
			 User user = userDao.getUserByName(j_username,j_organCode);
			 return user;
		}else if(null!=temp){
			User user = userDao.getUserByName(name);
			return user;
		}else{
			return null;
		}
		 
	}

	/**
	 * @param java.util.Map map
	 *  String username          用户名
	 *  String organcode         机构代码
	 * @return 用户对象
	 */
	public User getUserByMap(java.util.Map<String, String> map){
		if(null==userDao){
			System.out.println("User DAO is null");
			return null;
		}else{
			User user = userDao.getUserByMap(map);
			return user;
		}
	}
	
	public void updateByUserName(User u) {
		userDao.updateByUserName(u);
	}

	public void updatepassword(String id, String password) {
		userDao.updatepassword(id, password);
	}

	@Transactional(readOnly = true)
	public Page findByPageRequest(PageRequest<Map> q) {
		// TODO Auto-generated method stub
		return userDao.findByPageRequest(q);
	}

	public List getRoleByUserName(String userName) {
		List list = null;
		if (userName != null) {
			list = userDao.getRoleByUserName(userName);
		}
		return list;
	}

	public List getRoleRoleNameByUserName(String name) {
		List list = null;
		String[] temp = StringTool.SplitString(name, ",");
		String j_username ="";
		String j_organCode = "";
		if(null!=temp&&temp.length==2){
			 j_username = temp[0];
			 j_organCode = temp[1];
			 list = userDao.getRoleRoleNameByUserName(j_username,j_organCode);
			 return list;
		}else if(null!=temp){
			list = userDao.getRoleRoleNameByUserName(name);
			return list;
		}else{
			return null;
		}
	}
	/**
	 * 批量删除操作员
	 * @author bzq
	 */
	public Boolean  removeByIdArry(User u) {
		Boolean result =false;
		int i =-1,size=u.getIdList().size();
		i =userDao.removeByIdArry(u);
		if(i==size){
			result =true;
		}else{
			throw new RuntimeException();
		}
		return result;
	}


	public void save(User user) {
//		String password ="123456"; //SParametersHelper.getValue("password");
		String encode = EncodeDecodeUtil.base64Encode(user.getPassword());
		user.setPassword(encode);
		Timestamp regdate = new Timestamp(System.currentTimeMillis());
		user.setRegdate(regdate);
		user.setId(getNumberId(2));
		userDao.save(user);

		String sort = user.getRoleId();
		if (sort != null && sort.length() > 0) {
			sort = sort.replaceAll(" ", "");
			String[] roleArr = sort.split(",");

			for (int i = 0; i < roleArr.length; i++) {
				UserRole userRoleInsert = new UserRole();
				userRoleInsert.setUserId(user.getId());
				userRoleInsert.setRoleId(roleArr[i]);
				userRoleDao.save(userRoleInsert);
			}
		}
	}

	public void update(User user) {
		String encode = EncodeDecodeUtil.base64Encode(user.getPassword());
		user.setPassword(encode);
		userDao.update(user);
		
		String sort = user.getRoleId();
		if (sort != null && sort.length() > 0) {
			sort = sort.replaceAll(" ", "");
			String[] roleArr = sort.split(",");

			
			userRoleDao.deleteUserRoleList(user.getId());//首先删除已经存在的用户ID的角色
			
			for (int i = 0; i < roleArr.length; i++) {
				UserRole userRoleInsert = new UserRole();
				userRoleInsert.setUserId(user.getId());
				userRoleInsert.setRoleId(roleArr[i]);
				userRoleDao.save(userRoleInsert);
			}
		}

	}

	public void updateLogincountByUserName(String userName) {
		if (null != userName && !"".equals(userName)) {
			Map<String, Object> paras = new HashMap<String, Object>();
			paras.put("userName", userName);
			paras.put("lastloginDate", DateUtil.getTimestamp());
			userDao.updateLogincountByUserName(paras);
		}
	}

	/**
	 * 操作员 修改 个人信息
	 * @param u User
	 */
	public void personal(User user){ 
		super.update(user);
	}
	
	/**
	 * <p>查询操作角色集合中,最大权限的角色值</p>
	 * @param String userId 操作员ID
	 * @return 操作员拥有的最大权限的角色ID
	 * @author 鲍忠启
	 */
	@Transactional(readOnly = true)
	public String getUserMaxRoleId(String userId){ 
		Role role = new Role();
		role.setId("1");
		List role_list = roleDao.getSubsetTree(role);
		
		//从登录用户类中取当前用户信息
		UserInfo userInfo = LogonUser.logonUser();
		List user_role = userRoleDao.getUserRoleList(userInfo.getUserId()); 
		
		for(int i=0;i<role_list.size();i++){
			Role role_temp = (Role)role_list.get(i);
			for(int j=0;j<user_role.size();j++){
				UserRole userRole_temp = (UserRole)user_role.get(j);
				if(null!=role_temp&&null!=userRole_temp){
					String role_id_ = role_temp.getId();
					String usre_role_id = userRole_temp.getRoleId();
					if((null!=role_id_&&null!=usre_role_id)&&role_id_.equals(usre_role_id)){
						return role_id_;
					}
				}
			}
		}
		
		return null;
	}
}
